/**
 * 权限列表
 */

layui.config({
    base: '/js/layui_exts/treegrid/' //假设这是你存放拓展模块的根目录
}).extend({ //设定模块别名
    authtree: 'treegrid'
});

$(function () {

    let permList = JSON.parse(PERMISSION_TREE);
    // console.log(permList);
    // console.log("permIdList:" + typeof(permList));
    // console.log(Object.prototype.toString.call(permList));
    // console.log('permList', permList);
    //操作
    layui.use(['jquery', 'form', 'laytpl' , 'treegrid', 'layer'], function () {
        let $ = layui.jquery, laytpl = layui.laytpl, form = layui.form, treegrid = layui.treegrid, layer=layui.layer;

        form.verify({
           path: function (value) {
               if(value.length == 0){return '路劲不能为空';}
               if(value.length == 1 && value.substr(0, 1) == '/'){return;}
               if(!new RegExp('^(\\/\\w+)+$').test(value)){
                   return '无效的路劲'
               }
           }
        });

        treegrid.config.render = function (viewid, data) {
            let view = document.getElementById(viewid).innerHTML;
            return laytpl(view).render(data) || '';
        };

        let treeForm = treegrid.createNew({
            elem: 'permTable',
            view: 'view',
            data: {rows: permList},
            parentid: 'pid',
            singleSelect: false
        });
        treeForm.build();

        /**
         * 读取指定id的行数据
         * @param id
         * @return {*}
         */
        treeForm.getRowDataById = function(id){
            let tr = this.elem.find('.grid-body tr.treegrid-' + id);
            let index = tr.index();
            return this.pageData.rows[index];
        };

        /**
         * 设置表单数据
         * @param {*}
         */
        let setFormData = function(data){
            // console.log('表单赋值', data);
            //表单赋值
            form.val('permForm', data);
            //移除没有的值
            $.each($('#permForm input[name]'), function () {
                let name = $(this).attr('name');
                if(name){
                    if(! (name in data)){
                        $(this).val(null);
                    }
                }
            });
            //检查父节点
            let parentLabel = $('#permForm').find('>.layui-form-item>label[name=pid]');
            if('pid' in data){
                let name;
                if(data.pid){
                    let parentData = treeForm.getRowDataById(data.pid);
                    name = parentData.name;
                }else{
                    name = '根目录';
                }
                parentLabel.text(name);
                parentLabel.parent().removeClass('layui-hide');
            }else{
                parentLabel.parent().addClass('layui-hide')
            }
            // form.render(null, 'permForm');
        };

        /**
         * msg失败弹窗
         * @param msg
         */
        let msgError = function(msg){
            layer.msg(msg, {icon: 3});
        };

        //监听表单提交
        form.on('submit(permSubmit)', function (data) {
            //校验 TODO
            // console.log($("#permForm").serialize());
            let field = data.field;
            // console.log('表单提交field', field);
            let $elem = $(data.elem);

            //关闭弹窗
            let index = $elem.data('layerIndex');
            if(index){layer.close(index);}

            // console.log(data.elem);
            let callback = $elem.data('onSuccess');
            let loadingIndex = layer.load(2, {time: 5*1000});
            $.ajax({
                type: "POST",
                data: field,
                url: "/auth/setPerm",
                success: (res)=>{
                    if (res.code == 0) {
                        let data;
                        if(res.data && res.data.id){
                            data = res.data;
                        }else{
                            data = field;
                        }
                        //回调
                        if(callback){
                            try{
                                console.log('callback=>', data);
                                callback(data);
                            }catch (e) {
                                console.log(e);
                                msgError("出错啦")
                            }
                            layer.msg('成功', {icon: 1});
                        }
                    }else{
                        msgError(res.msg || "失败")
                    }
                },
                error: (res)=>{
                    msgError(res.status || "请求错误");
                },
                complete: ()=>{
                    layer.close(loadingIndex);
                }
            });
            return false;
        });
        form.render();

        /**
         * 打开表单弹窗
         * @param {string} title
         * @param {{*}} formData
         * @param {function} successCallback
         */
        let openFormLayer = function(title, formData, successCallback){
            setFormData(formData);
            layer.open({
                type: 1,
                title: "更新权限",
                fixed: false,
                resize: false,
                shadeClose: true,
                area: ['500px', '580px'],
                content: $('#updatePerm'),
                btn: ['确认', '重置', '取消'],
                success: function(layero, index){
                    // console.log(layero, index);
                    let submitButton = $('#permSubmit');
                    submitButton.data('formData', formData);
                },
                yes: function (index, layero) {
                    // let field = form.val('permForm');
                    // console.log('field', field);
                    // treeForm.updateNode(field, formData.id);
                    // console.log(layero);

                    let submitButton = $('#permSubmit');
                    if(successCallback){
                        //提交成功的回调
                        submitButton.data('onSuccess', successCallback).data('layerIndex', index);
                    };
                    //点击表单按钮, 让表单提交(可以触发表单校验功能)
                    submitButton.click();
                    // layer.close(index);
                    return true;
                },
                btn2: function () {
                    setFormData(formData);
                    return false
                },
                btn3: function () {
                    return true
                }
            });
        };

        /**
         * 工具栏按钮事件回调
         * @param e
         */
        let onToolButtonClick = function(e){
            // console.log(this, e);
            let id = $(this).data('id');
            if(!id){return;}
            let event = $(this).data('event');
            if(!event){return;}

            //复制一遍rowData
            let formData = {};
            let rowData = treeForm.getRowDataById(id);
            for(let k in rowData){
                formData[k] = rowData[k];
            }

            // console.log('formData ', formData );
            e.preventDefault(); //阻止事件冒泡

            switch (event) {
                case 'add':
                    formData.type = 1;
                    formData.pid = rowData.id; //将添加的结点作为所选结点的子节点
                    delete formData.id;

                    openFormLayer("新增", formData, (permission)=> {
                        // console.log('添加成功', permission);
                        if(permission.pid){
                            treeForm.insertChild(permission, permission.pid);
                            //注册工具按钮事件
                            let tr = treeForm.elem.find('.grid-body tr.treegrid-' + permission.id);
                            // console.log('tr', tr);
                            tr.find('a[data-id]').on('click', onToolButtonClick);
                        }
                    });
                    break;
                case 'edit':
                    formData.type = 0; //编辑
                    openFormLayer("编辑", formData, (permission)=> {
                        treeForm.updateNode(permission, permission.id);
                        //注册工具按钮事件
                        let tr = treeForm.elem.find('.grid-body tr.treegrid-' + permission.id);
                        tr.find('a[data-id]').on('click', onToolButtonClick);
                    });
                    break;
                case 'del':
                    layer.confirm('您确定要删除' + formData.name + '权限吗？', {
                        btn: ['确认', '取消'] //按钮
                    }, function () {
                        let loadingIndex = layer.load(2, {time: 5*1000});
                        $.ajax({
                            type: 'POST',
                            url: '/auth/del',
                            data: {"id": formData.id},
                            success: (res)=>{
                                if (res.code == 0) {
                                    treeForm.deleteNode(formData.id);
                                    layer.msg('成功', {icon: 1});
                                }else{
                                    layer.msg(res.msg, {icon: 3});
                                }
                            },
                            error: (res)=>{
                                layer.msg(res.status || '错误', {icon: 3});
                            },
                            complete: ()=>{
                                layer.close(loadingIndex);
                            }
                        });
                    }, function () {
                        return true;
                    });
                    break;
            }
        };

        //监听表格中工具按钮点击事件
        $('#permTable .grid-body tr a[data-id]').on('click', onToolButtonClick);

        //监听新增跟结点按钮事件
        $('#addRootPermButton').on('click', function () {
            let formData = {
                type: 1, //添加根权限
                istype: 0,
                pid: 0
            };
            openFormLayer('添加根权限', formData, (permission)=> {
                console.log('添加成功', permission);
                if(permission.pid){return;}
                //为根节点
                treeForm.insertNode(permission, 0);
                //注册工具按钮事件
                let tr = treeForm.elem.find('.grid-body tr.treegrid-' + permission.id);
                // console.log('tr', tr);
                tr.find('a[data-id]').on('click', onToolButtonClick)

            });
        })
    });

});


/**
 * 模板装饰器
 * @type {{page:function, type:function}}
 */
const TEMPLATE_DECORATOR = (function () {

    /**
     * 路劲装饰器
     * @param {string} path
     * @return string || undefined
     */
    let Page = function (path) {
        if(!path){return "";}
        let pathList = path.split('/');
        if(pathList.length == 1){
            //根目录
            return '<label class="path-separator"> > </label><label class="path-label">' + pathList[0] + '</label>';
        }else{
            if(pathList[pathList.length-1] == ''){
                pathList.splice(pathList.length-1, 1); //移除最后一个空字符
            }

            if(pathList[0] == ''){
                pathList.splice(0, 1); //移除第一个空字符
            }
            if(pathList.length == 0){
                return '<label class="path-label">根目录</label>';
            }
            let res = [];
            pathList.forEach((each)=>{
                res.push('<label class="path-separator"> > </label>');
                res.push('<label class="path-label">' + each + '</label>');
            });
            return res.join('');
        }
        return path;
    };

    /**
     * 路劲装饰器
     * @param {number || string} typeId
     * @return string || undefined
     */
    let Type = function (typeId) {
        if(typeId == undefined){return "";}
        try{
            typeId = parseInt(typeId);
        }catch (e) {
            return "";
        }
        switch (typeId) {
            case 0:
                return `<label class="type-label"> <i class="layui-icon layui-icon-layer"></i>菜单 </label>`;
            case 1:
                return `<label class="type-label"><i class="layui-icon layui-icon-component"></i> 功能组 </label>`;
        }
        return "";
    };

    return{
        page: Page,
        type: Type
    }
})();